package com.lamda.zhekou.controller;

import com.lamda.zhekou.exception.ZheKouException;
import com.lamda.zhekou.manager.ServerHostManager;
import com.lamda.zhekou.manager.VPSRecordManager;
import com.lamda.zhekou.model.ServerHost;
import com.lamda.zhekou.model.User;
import com.lamda.zhekou.model.UserVps;
import com.lamda.zhekou.model.VPS;
import com.lamda.zhekou.vo.HostVo;
import com.lamda.zhekou.vo.ResultVo;
import com.lamda.zhekou.vo.UserVpsVo;
import com.lamda.zhekou.vo.VpsVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by MJiao on 15/8/16.
 */
@Controller
public class HostSeverController {

    @Autowired
    private ServerHostManager serverHostManager;

    @Autowired
    private VPSRecordManager vpsRecordManager;

    @RequestMapping(value = "/getHostByFilter")
    @ResponseBody
    public List<HostVo> getHostsByFilter(@RequestParam(value = "keyWord", required = false) String keyWord) {
        if (StringUtils.isEmpty(keyWord)) {
            return new ArrayList<>();
        }
        return this.serverHostManager.getHostsByFilter(keyWord);

    }

    @RequestMapping(value = "/getVpsById")
    @ResponseBody
    public VPS getVpsById(@RequestParam(value = "vpsId", required = true) Long vpsId) {

        return this.serverHostManager.getVpsByVpsId(vpsId);

    }

    @RequestMapping(value = "/getUserVps")
    @ResponseBody
    public UserVps getUserVps(@RequestParam(value = "userVpsId", required = true) Long userVpsId) {

        return this.serverHostManager.getUserVpsByUVId(userVpsId);

    }

    @RequestMapping(value = "/getVpsByHostId")
    @ResponseBody
    public Set<VPS> getVpsByHostId(@RequestParam(value = "hostIp", required = true) String hostIp) {
        if (StringUtils.isEmpty(hostIp)) {
            return new HashSet<>();
        }
        ServerHost serverHost = this.serverHostManager.fgetServerHostByIp(hostIp);
        if (serverHost == null) {
            return new HashSet<>();
        }
        return serverHost.getVpsSet();

    }

    @RequestMapping(value = "/getVpsByFilter")
    @ResponseBody
    public List<VpsVo> getVpsesByFilter(@RequestParam(value = "keyWord", required = false) String keyWord) {
        if (StringUtils.isEmpty(keyWord)) {
            return new ArrayList<>();
        }
        //return  this.serverHostManager.getVpsesByFilter(keyWord);
        return new ArrayList<>();
    }

    @RequestMapping(value = "/recordVps", method = RequestMethod.GET)
    public String recordVps(HttpServletRequest httpServletRequest, Model model) {

        User user = (User) httpServletRequest.getSession().getAttribute("loginedUser");
        int vpsRecordCountByUserId = this.vpsRecordManager.getVPSRecordCountByUserId(user.getId());

        List<ServerHost> allServerHosts = this.serverHostManager.getAllServerHosts();
        model.addAttribute("vpsRecordCount", vpsRecordCountByUserId);
        model.addAttribute("allServerHosts", allServerHosts);


        return "recordVps";
    }

    /**
     * 续费
     *
     * @param httpServletRequest
     * @param userVpsId
     * @param expireTimeStr      截止时间
     * @param rmb                rmb
     * @return
     */
    @RequestMapping(value = "/doRenewVps")
    @ResponseBody
    public ResultVo doRenewVps(HttpServletRequest httpServletRequest,
                               @RequestParam(value = "userVpsId", required = true) Long userVpsId,
                               @RequestParam(value = "renewExpireTime", required = true) String expireTimeStr,
                               @RequestParam(value = "renewRmb", required = true) float rmb) {
        ResultVo resultVo = new ResultVo();
        resultVo.setMsg("续费成功");
        resultVo.setSucc(true);
        User loginedUser = (User) httpServletRequest.getSession().getAttribute("loginedUser");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒");

        Timestamp expireTime = null;
        try {

            expireTime = new Timestamp(simpleDateFormat.parse(expireTimeStr).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
            resultVo.setMsg("参数错误,登记失败");
            resultVo.setSucc(false);
            return resultVo;
        }

        try {
            this.serverHostManager.renewVps(loginedUser.getId(), userVpsId, expireTime, rmb);

        } catch (ZheKouException e) {
            resultVo.setMsg(e.getMessage());
            resultVo.setMsg(e.getMessage());
            resultVo.setSucc(false);
        }

        return resultVo;

    }

    /**
     * 暂停用户的vps
     *
     * @param userVpsId
     * @return
     */
    @RequestMapping(value = "/disableUserVps")
    @ResponseBody
    public ResultVo disableUserVps(HttpServletRequest httpServletRequest,
                                   @RequestParam(value = "userVpsId", required = true) Long userVpsId) {
        ResultVo resultVo = new ResultVo();
        resultVo.setMsg("停用成功");
        resultVo.setSucc(true);


        User loginedUser = (User) httpServletRequest.getSession().getAttribute("loginedUser");
        try {
            this.serverHostManager.disableUserVps(loginedUser.getId(), userVpsId);

        } catch (ZheKouException e) {
            resultVo.setMsg(e.getMessage());
            resultVo.setMsg(e.getMessage());
            resultVo.setSucc(false);
        }
        return resultVo;

    }

    @RequestMapping(value = "/doInitVPS")
    @ResponseBody
    public ResultVo doInitVPS(HttpServletRequest httpServletRequest,
                              @RequestParam(value = "userVpsId", required = true) Long userVpsId) {
        ResultVo resultVo = new ResultVo();
        resultVo.setMsg("初始化成功");
        resultVo.setSucc(true);


        User loginedUser = (User) httpServletRequest.getSession().getAttribute("loginedUser");
        try {
            this.serverHostManager.doInitVPS(loginedUser.getId(), userVpsId);

        } catch (ZheKouException e) {
            resultVo.setMsg(e.getMessage());
            resultVo.setMsg(e.getMessage());
            resultVo.setSucc(false);
        }
        return resultVo;

    }

    @RequestMapping(value = "/doRecordVps")
    @ResponseBody
    public ResultVo doRecordVps(HttpServletRequest httpServletRequest,
                                @RequestParam(value = "rmb", required = true) float rmb,
                                @RequestParam(value = "serverHostId", required = true) Long serverHostId,
                                @RequestParam(value = "vpsName", required = true) String vpsName,
                                @RequestParam(value = "buyVpsId", required = true) Long vpsId,
                                @RequestParam(value = "buyType") int buyType,
                                @RequestParam(value = "expireTime", required = true) String expireTimeStr,
                                @RequestParam(value = "userEmail", required = true) String userEmail) {
        ResultVo resultVo = new ResultVo();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 hh时mm分ss秒");

        Timestamp expireTime = null;
        try {

            expireTime = new Timestamp(simpleDateFormat.parse(expireTimeStr).getTime());
        } catch (ParseException e) {
            e.printStackTrace();
            resultVo.setMsg("参数错误,登记失败");
            resultVo.setSucc(false);
            return resultVo;
        }
        try {

            User loginedUser = (User) httpServletRequest.getSession().getAttribute("loginedUser");

            this.serverHostManager.registerVps(loginedUser.getId(), userEmail, serverHostId, vpsId, expireTime,buyType, rmb);
            resultVo.setMsg("登记成功");
            resultVo.setSucc(true);
        } catch (ZheKouException e) {
            resultVo.setMsg(e.getMessage());
            resultVo.setMsg(e.getMessage());
            resultVo.setSucc(false);
        }
        return resultVo;
    }

    @RequestMapping(value = "/hostList")
    public String hostList(Model model) {

        List<ServerHost> allServerHosts = this.serverHostManager.getAllServerHosts();
        model.addAttribute("serverHostList", allServerHosts);
        return "hostList";
    }

    @RequestMapping(value = "/getServerHost")
    public String getServerHost(Model model, @RequestParam(value = "serverHostId", required = true) Long serverHostId) {
        ServerHost serverHost = this.serverHostManager.getServerHostById(serverHostId);
        //查询已经出售的vps
        List<UserVps> userVpsList = new ArrayList<>();
        if (serverHost.getVpsSet() != null && serverHost.getVpsSet().size() != 0) {
            userVpsList.addAll(this.serverHostManager.getUserVpsListBy(serverHost.getVpsSet()));
        }

        List<UserVpsVo> userVpsVoList = UserVpsVo.fromUserVpsList(userVpsList);
        //已经出售的vps
        List<VPS> buyedVpsList = new ArrayList<>();
        for (UserVps userVps : userVpsList) {
            buyedVpsList.add(userVps.getVps());
        }
        //没有出售的vps
        Collection noSaleVpsCollection = CollectionUtils.subtract(serverHost.getVpsSet(), buyedVpsList);
        for (Object o : noSaleVpsCollection) {
            VPS vps = (VPS) o;
            UserVpsVo userVpsVo = new UserVpsVo();
            userVpsVo.setUserVpsId(-1l);
            userVpsVo.setEmail("---");
            userVpsVo.setStatus(vps.getStatus());
            userVpsVo.setLeftTime("---");
            userVpsVo.setStatusLastRefreshTime(vps.getStatusLastRefreshTime());
            userVpsVo.setIp(vps.getIp());
            userVpsVo.setOs(vps.getOs());
            userVpsVo.setVpsName(vps.getVmName());
            userVpsVo.setVpsId(vps.getId());

            userVpsVoList.add(userVpsVo);
        }



        model.addAttribute("serverHost", serverHost);
        model.addAttribute("userVpsVoList", userVpsVoList);
        model.addAttribute("hasSaleCount", userVpsVoList.size() - noSaleVpsCollection.size());
        model.addAttribute("avaSaleCount", noSaleVpsCollection.size());
        return "serverHostDetail";
    }


}
